const Proxy = require('../../proxy')
const webDataUtil = require('../../util/webDataUtil')
const reqlib = require('app-root-path').require
const btbAs = reqlib('/app/common/btb')
const mBuySell = reqlib('/app/common/btb/mBuySell')
const quantityUtil = reqlib('/app/common/btb/quantityUtil')

const BtbIndex = Proxy.BtbIndex
const Dictionary = Proxy.Dictionary

const exBuy = reqlib('/app/common/btb/exBuy')
const exSell = reqlib('/app/common/btb/exSell')

// 现货买卖15m
module.exports = async function () {
  const btbOpen = await Dictionary.findOne({ key: 'btbOpen' })
  if (!(btbOpen && btbOpen.value === 'true')) {
    return false
  }
  // 找出币
  let btbRes = await BtbIndex.find({
    status: 1,
    xh_status: 1
  }, {
    sort: '-proportion'
  })
  // 总占比
  const btbIndexConfig = {
    proportionAll: 0,
    balance: {},
    btbList: []
  }
  // 查K线
  for (let i = 0; i < btbRes.length; i++) {
    const btbItem = btbRes[i]
    if (btbItem.proportion) {
      btbIndexConfig.proportionAll += btbItem.proportion
      // K线
      const klineRes = await webDataUtil.getBIBTKlines({
        name: `${btbItem.code}`,
        interval: '15m'
      })
      const asInfo = await btbAs.getItemInfoList(klineRes)
      let asList = [...asInfo]
      // 让近的在前面
      asInfo.reverse()
      const asToday = asInfo[0] || {}
      btbIndexConfig.btbList.push({
        name: btbItem.name,
        code: btbItem.code,
        hourEma510: btbItem.hourEma510 || 0,
        hourEmaInfo: btbItem.hourEmaInfo ? btbItem.hourEmaInfo : {},
        strategy: btbItem.strategy,
        min_qty: btbItem.min_qty,
        max_qty: btbItem.max_qty,
        step_size: btbItem.step_size,
        tick_size: btbItem.tick_size,
        min_notional: btbItem.min_notional,
        proportion: btbItem.proportion,
        close: asToday.close,
        asInfo: [asToday],
        asList: asList
      })
    }
  }
  let btbHyMinLen = await Dictionary.findOne({ key: 'btbXhMinLen' })
  if (btbHyMinLen && btbHyMinLen.value) {
    btbHyMinLen = parseInt(btbHyMinLen.value) || 3
  } else {
    btbHyMinLen = 3
  }
  if (btbIndexConfig.proportionAll < btbHyMinLen) {
    btbIndexConfig.proportionAll = btbHyMinLen
  }
  if (btbIndexConfig.btbList.length === 0) {
    return false
  }
  // 资产
  const balanceRes = await webDataUtil.binance('getBalance')
  const myBalance = balanceRes.data || {}
  let all = 0
  btbIndexConfig.btbList.forEach((v, index) => {
    const available = parseFloat(myBalance[v.code].available)
    btbIndexConfig.btbList[index] = {
      ...v,
      balance: available,
      usdt: available * v.close
    }
    btbIndexConfig.balance[v.code] = available
    all += available * v.close
  })
  const usdtAvailable = parseFloat(myBalance['USDT'].available)
  btbIndexConfig.balance['USDT'] = usdtAvailable
  all += usdtAvailable
  btbIndexConfig.balance['ALL'] = all
  // 操作信息
  let btbOpInfo = await Dictionary.findOne({ key: 'btbOpInfo' })
  let btbOpInfoJson = {}
  if (btbOpInfo && btbOpInfo.value) {
    btbOpInfoJson = JSON.parse(btbOpInfo.value)
  } else {
    btbOpInfoJson = {}
  }
  // 分析
  btbIndexConfig.btbList.forEach((btbItem) => {
    if (btbItem.strategy === '1') {
      btbItem.asRes = mBuySell.buySell1Flag(btbItem, btbOpInfoJson)
    } else if (btbItem.strategy === '2') {
      btbItem.asRes = mBuySell.buySell2Flag(btbItem, btbOpInfoJson)
    } else if (btbItem.strategy === '3') {
      btbItem.asRes = mBuySell.buySell3Flag(btbItem, btbOpInfoJson)
    } else if (btbItem.strategy === '5') {
      btbItem.asRes = mBuySell.buySell5Flag(btbItem, btbOpInfoJson)
    } else if (btbItem.strategy === '4') {
      btbItem.asRes = mBuySell.buySellFlag(btbItem, btbOpInfoJson)
    } else {
      btbItem.asRes = mBuySell.buySellFlag(btbItem, btbOpInfoJson)
    }
  })
  // 执行买入卖出
  for (let i = 0; i < btbIndexConfig.btbList.length; i++) {
    const btbItem = btbIndexConfig.btbList[i]
    const asRes = btbItem.asRes
    if (asRes.buy || asRes.sell) {
      let asInfo = {
        rate: 1,
        type: 0
      }
      if (asRes.buy) {
        asInfo.rate = asRes.buyRate || 1
        asInfo.type = 0
      } else {
        asInfo.rate = asRes.sellRate || 1
        asInfo.type = 1
      }
      const val = quantityUtil.getQuantity(asInfo, btbItem, btbIndexConfig)
      asRes.val = val
      if (val) {
        if (asRes.buy) {
          await exBuy({
            usdtKey: `${btbItem.code}USDT`,
            quantity: val,
            btbItem
          })
          // if (info) {
          //   btbIndexConfig.balance.USDT = btbIndexConfig.balance.USDT - info.useUsdt
          // }
        } else {
          await exSell({
            usdtKey: `${btbItem.code}USDT`,
            quantity: val,
            btbItem
          })
          // if (info) {
          //   btbIndexConfig.balance.USDT = btbIndexConfig.balance.USDT + info.getUsdt
          // }
        }
      }
    }
  }
  await Dictionary.update({ key: 'btbOpInfo' }, {
    value: JSON.stringify(btbOpInfoJson)
  })
  return btbIndexConfig
}
